import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import router from 'umi/router';
import {
  querySmallWhiteDetail,
  queryLogisList,
  operSaveOrDelNo,
  operSaveOrUpdate,
} from './service';
import { fetchValidation } from '@/utils';

export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    fetchLogis: Effect;
    saveOrDelNo: Effect;
    saveOrUpdate: Effect;
  };
  reducers: {
    save: Reducer;
    saveLog: Reducer;
    clear: Reducer;
  };
}

const stateData = {
  detailInfo: {},
  logisList: [],
};

const Model: ModelType = {
  namespace: 'cooperationCompanySmallWhiteAdd',

  state: stateData,

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(querySmallWhiteDetail, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: response.body,
      });
    },

    * fetchLogis({ payload }, { call, put }) {
      const response = yield call(queryLogisList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'saveLog',
        payload: data.body && data.body.list ? data.body.list : [],
      });
    },

    * saveOrDelNo({ payload: { id, ...query } }, { call, put }) {
      const response = yield call(operSaveOrDelNo, query);
      const data = fetchValidation(response);
      if (data) {
        message.success(query.isValid === 1 ? '添加成功' : '删除成功');
        yield put({
          type: 'fetch',
          payload: { id },
        });
      }
    },

    * saveOrUpdate({ payload }, { call, put }) {
      const response = yield call(operSaveOrUpdate, payload);
      const data = fetchValidation(response);
      if (data) {
        message.success(payload.id ? '保存成功' : '添加成功');
        router.goBack();
      }
    },
  },

  reducers: {
    save(state, action) {
      return {
        ...state,
        detailInfo: action.payload,
      };
    },

    saveLog(state, action) {
      return {
        ...state,
        logisList: action.payload,
      };
    },

    clear(state, action) {
      return stateData;
    },
  },
};

export default Model;
